package com.virtualperson.service.impl;

import com.virtualperson.dto.ImageValidationResponse;
import com.virtualperson.service.ImageValidationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class ImageValidationServiceImpl implements ImageValidationService {

    @Value("${aliyun.api-key}")
    private String apiKey;

    private static final String API_URL = "https://dashscope.aliyuncs.com/api/v1/services/aigc/image2video/face-detect";

    @Override
    public ImageValidationResponse validateImage(String imageUrl) {
        log.info("收到图片检测请求，imageUrl={}", imageUrl);
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + apiKey);

        Map<String, Object> body = new HashMap<>();
        body.put("model", "liveportrait-detect");
        Map<String, String> input = new HashMap<>();
        input.put("image_url", imageUrl);
        body.put("input", input);

        log.info("即将请求阿里云图片检测API，url={}, body={}", API_URL, body);
        try {
            HttpEntity<Map<String, Object>> request = new HttpEntity<>(body, headers);
            ResponseEntity<Map> response = restTemplate.postForEntity(API_URL, request, Map.class);
            log.info("阿里云图片检测响应：status={}, body={}", response.getStatusCode(), response.getBody());

            Map output = (Map) ((Map) response.getBody()).get("output");
            boolean pass = false;
            String message = "未知错误";
            if (output != null) {
                Object passObj = output.get("pass");
                if (passObj instanceof Boolean) {
                    pass = (Boolean) passObj;
                }
                Object msgObj = output.get("message");
                if (msgObj instanceof String) {
                    message = (String) msgObj;
                }
            }
            ImageValidationResponse result = new ImageValidationResponse();
            result.setPass(pass);
            result.setMessage(message);
            log.info("图片检测结果：pass={}, message={}", pass, message);
            return result;
        } catch (Exception e) {
            log.error("图片检测请求异常", e);
            ImageValidationResponse result = new ImageValidationResponse();
            result.setPass(false);
            result.setMessage("图片检测异常: " + e.getMessage());
            return result;
        }
    }
} 